﻿//
// Created by 86152 on 2021/5/6.
//

#include "Utils.h"
#include <cstdlib>
#include <ctime>
#include <iostream>

namespace Utils{


    void TreeManager::linkNode(std::vector<TreeNode *> &pool){
        int size = pool.size();
        for (int i = 0; i < size; ++i) {
            if (i * 2 + 1 < size){
                pool[i]->left = pool[i * 2 + 1];
            }
            if (i * 2 + 2 < size){
                pool[i]->right = pool[i * 2 + 2];
            }
        }
    }


    // 获取根
    TreeNode* TreeManager::getTreeRoot(int n, int min, int max) {
        fillTreePool(pool, n, min, max);
        linkNode(pool);
        return pool.front();
    }

    TreeNode* TreeManager::getTreeRoot(int* list, int length) {
        for (int i = 0; i < length; ++i) {
            TreeNode* v = new TreeNode();
            v->value = list[i];
            v->left = nullptr;
            v->right = nullptr;
            pool.push_back(v);
        }
        linkNode(pool);
        return pool.front();
    }

    TreeNode* TreeManager::getThreadTreeRoot(int n, int min, int max) {
        fillThreadTreePool(pool, n, min, max);
        linkNode(pool);
        return pool.front();
    }

    TreeNode* TreeManager::getThreadTreeRoot(int* list, int length) {
        for (int i = 0; i < length; ++i) {
            ThreadTreeNode* v = new ThreadTreeNode();
            v->value = list[i];
            v->left = nullptr;
            v->right = nullptr;
            v->ltag = 0;
            v->rtag = 0;
            pool.push_back(v);
        }
        linkNode(pool);
        return pool.front();
    }


    // 销毁树
    void TreeManager::destory() {
        std::cout << "destory tree..." << std::endl;
        for(TreeNode* ptr : this->pool){
            delete  ptr;
        }
        std::cout << "destory finish..." << std::endl;
    }

    void TreeManager::fillTreePool(std::vector<TreeNode *> &pool, int n, int min, int max) {
        srand((unsigned )time(nullptr));
        for (int i = 0; i < n; ++i) {
            TreeNode* v = new TreeNode();
            v->value = rand() % (max - min) + min;
            v->left = nullptr;
            v->right = nullptr;
            pool.push_back(v);
        }
    }

    void TreeManager::fillThreadTreePool(std::vector<TreeNode *> &pool, int n, int min, int max) {
        srand((unsigned )time(nullptr));
        for (int i = 0; i < n; ++i) {
            ThreadTreeNode* v = new ThreadTreeNode();
            v->value = rand() % (max - min) + min;
            v->left = nullptr;
            v->right = nullptr;
            v->ltag = 0;
            v->rtag = 0;
            pool.push_back(v);
        }
    }
}